package com.stores.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.stores.action.ManageProductAction;
import com.stores.model.Product;
import com.stores.model.Variation;
import com.stores.toolset.WebAction;

public class ProductsController extends HttpServlet {

	private static final String ADMIN_MANAGE_PRODUCT_JSP = "/admin/manage-product.jsp";
	private static final String ADMIN_PRODUCT_LOAD_VARIATION = "/admin/product/load/variation";
	private static final String ADMIN_PRODUCT_LOAD_PREREQUISITE = "/admin/product/load/prerequisite";
	private static final String ADMIN_PRODUCT_LOAD = "/admin/product/load";
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/***
	 * 
	 */
	@SuppressWarnings("static-access")
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		ServletContext context = getServletContext();
		String requestUrl = request.getRequestURL().toString();
		if (requestUrl.indexOf("manage-products") > -1) {
			RequestDispatcher dispatcher = context
					.getRequestDispatcher(ADMIN_MANAGE_PRODUCT_JSP);
			try {
				dispatcher.forward(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}
		} else {
			try {
				response.sendError(response.SC_BAD_REQUEST,
						"Valid url is /admin/manage-products");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}
		}
	}

	/***
	 * 
	 */
	// @SuppressWarnings("static-access")
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		WebAction webAction = new WebAction(request, response);
		ManageProductAction manage = new ManageProductAction();
		// InputValidator validator = new InputValidator();

		if (webAction.isUrl(ADMIN_PRODUCT_LOAD)) {
			webAction.writeJsonResponse(manage.Retrieve());
		} else if (webAction.isUrl(ADMIN_PRODUCT_LOAD_PREREQUISITE)) {
			webAction.writeJsonResponse(manage.RetrievePrerequisites());
		} else if (webAction.isUrl(ADMIN_PRODUCT_LOAD_VARIATION)) {
			long categoryId = webAction.parseJsonRequest(Variation.class)
					.getCategoryId();
			webAction.writeJsonResponse(manage.RetrieveVariations(categoryId));
		} else {
			// ProductInsertViewModel product = webAction
			// .parseJsonRequest(ProductInsertViewModel.class);
			// manage.Create(product.ToEntity());
			Product product = webAction.parseJsonRequest(Product.class);
			manage.Create(product);
		}
	}
}
